<template>
  <el-card style="">

    <el-row>
      <el-col :span="5">
        <el-menu
            default-active="1"
            class="el-menu-vertical-demo"
            active-text-color="#ffd04b"
            background-color="#545c64"
            text-color="#fff"
            style="height: 700px;overflow-y:auto;"
        >
          <el-sub-menu v-for="(item,index) in cameraArray" :index="index" :key="item.id">
            <template #title>
              <span>{{ item.org_name }}</span>
            </template>
            <el-menu-item-group>
              <el-menu-item :index="index+1+'-'+indexx" @click="selectPlayer(itemC)" v-for="(itemC,indexx) in item.camera_list">{{itemC.camera_name}}</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>

          <el-sub-menu index="2">
            <template #title>

              <span>其他</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="2-1" @click="goPage('/exceptioninfo')">item one</el-menu-item>
              <el-menu-item index="2-2">item two</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </el-menu>
      </el-col>

      <el-col :span="19">
        <!--      <RtspPlayer ref="rtspPlayerRef"></RtspPlayer>-->
        <div>
          <div style="height: 100%;width: 100%;display: flex;align-items: center;justify-content: center;">
            <div class="video" v-show="isPlay" :id="elId"></div>
            <div v-show="!isPlay" style="color: #08979C;font-size: 25px;">暂无视频源</div>
          </div>
        </div>
      </el-col>

    </el-row>

  </el-card>
</template>


<script lang="ts" setup>
// import '../assets/index.css'
// import '../assets/iconfont.css'

import {ref, onMounted, reactive,toRefs} from 'vue'
import FlvJsPlayer from 'xgplayer-flv.js';//在shim-vue.d.ts，中加上declare module 'xgplayer-flv.js'；因为这个没有ts版本，只有js
import Player from 'xgplayer';

import { guid } from './utils/util';
import {CameraListItem} from "@/entityapi/base";
import {getCameraListArrayAPI, getRtspById} from "@/api/cameraapi";
import {ElMessage} from "element-plus";
const stateCamera=reactive({
  cameraArray: [] as CameraListItem[],
  playFlag:1
})
const {
  cameraArray,
}=toRefs(stateCamera)

const isPlay = ref(false)
const player = ref<any>({})
const elId = guid()
//const elId = "111111111"


onMounted(() => {
  const testa={
    org_name:"工区1",
    camera_list:[
      {
        id:21,
        camera_name:"string",
        org_name:"string",
        video_url:"rtsp://admin:Gld12345@192.168.1.2:554//Streaming/Channels/101",
        pull_url:"string",
        identify_type:"安全帽",
        begin_time:"08:30",
        end_time:"08:22",
      },
      {
        id:2,
        camera_name:"string",
        org_name:"string",
        video_url:"rtsp://123.131.131.182:554/openUrl/3za0Sty",
        pull_url:"string",
        identify_type:"安全帽",
        begin_time:"08:30",
        end_time:"08:22",
      }
    ]
  }
  const testb={
    org_name:"工区2",
    camera_list:[
      {
        id:3,
        camera_name:"string",
        org_name:"string",
        video_url:"string",
        pull_url:"string",
        identify_type:"安全帽",
        begin_time:"08:30",
        end_time:"08:22",
      },
      {
        id:4,
        camera_name:"string",
        org_name:"string",
        video_url:"ws://localhost:8866/live?url=rtsp://admin:Gld12345@192.168.1.2:554//Streaming/Channels/101",
        pull_url:"string",
        identify_type:"安全帽",
        begin_time:"08:30",
        end_time:"08:22",
      }
    ]
  }
  stateCamera.cameraArray.push(testa)
  stateCamera.cameraArray.push(testb)

  console.log('computed执行');
  getCameraListArrayAPI().then((res:any)=>{
    console.log(res)
    if(res.code==200){
      stateCamera.cameraArray=res.data
    }
    //console.log(stateCamera.cameraArray)
  })

  //createPlayer('ws://localhost:8866/live?url=rtsp://admin:Gld12345@192.168.1.2:554//Streaming/Channels/101', true, 0)
  document.addEventListener('visibilitychange', function () {
    // console.log(document.visibilityState);
    // console.log(document.hidden);
    if (document.hidden) {
      console.log("页面隐藏")
    }
  });
})

function selectPlayer(val:any){
  getRtspById(val.id).then((res:any)=>{
    if (res.code==200){
      console.log("获取的RTSP："+res.url)

      //开始只运行一次playCmaera，后面更改url就行不能总是运行
      if(stateCamera.playFlag==1){
        playCamera(res.url,val.id)
        stateCamera.playFlag=2
      }else {
        changeVideo('ws://localhost:8866/live?url='+res.url)
      }

      //changeVideo(res.url)
    }else{
      ElMessage({
        showClose: true,
        message: '获取失败，请重试',
        type: 'error',
      })
    }
  })
}

const playCamera=(videourl:string,id:number)=>{
  //closePlayer()
  console.log(videourl)
  //var randonm=Math.floor(Math.random() * (10000 - 0 + 1)) + 0
  createPlayer('ws://localhost:8866/live?url='+videourl, true, id)
}


const createPlayer = (url: string, hasCloseBtn: boolean, index: number) => {
  //const elId = guid()
  console.log(url);
  console.log(hasCloseBtn);
  console.log(index);

  if (!url) {
    return;
  }

  // if (player) {
  //     changeVideo(url);
  //     return;
  // }

  isPlay.value = true;
  player.value = new FlvJsPlayer({
    id: elId,
    url: url,
    // fitVideoSize: 'auto',
    fluid: true,
    autoplay: true,
    isLive: true,
    playsinline: false,
    screenShot: true,
    whitelist: [''],
    ignores: ['time'],
    closeVideoClick: true,
    // errorTips: '<span class="app-error">无视频源</span>',
    customConfig: {
      isClickPlayBack: false
    },
    flvOptionalConfig: {
      enableWorker: true,
      enableStashBuffer: true, //启用缓存
      stashInitialSize: 4096, //缓存大小4m
      lazyLoad: false,
      lazyLoadMaxDuration: 40 * 60,
      autoCleanupSourceBuffer: true,
      autoCleanupMaxBackwardDuration: 35 * 60,
      autoCleanupMinBackwardDuration: 30 * 60
    } //flv.js可选配置项 [flv.js配置](https://github.com/bilibili/flv.js/blob/master/docs/api.md#config)
  });

  // 自定义播放器按钮
  // let divStr =
  //   '<i class="btn-hover el-icon-camera button-screen-shot" style="font-size: 23px;margin-right: 10px;pointer-events: auto;"></i>' +
  //   '<i class="btn-hover el-icon-s-tools button-set" style="font-size: 23px;margin-right: 10px;pointer-events: auto;"></i>' +
  //   '<i class="btn-hover el-icon-video-camera-solid button-history" style="font-size: 23px;margin-right: 10px;pointer-events: auto;"></i>';

  let divStr = '<i class="btn-hover el-icon-d-arrow-left button-playback" style="font-size: 23px;pointer-events: auto;"></i>';

  let divClose = '<i @click="closePlayer" class="btn-hover el-icon-close app-close-btn-c"></i>';

  let util = Player.util;
  // let customBtn = util.createDom('div', divStr, {}, 'flex align-center justify-center app-player-button'); //'div', divStr, {}, 'class'
  let customBtn = util.createDom(
      'div',
      divStr,
      { style: 'width: 40px;heigth:40px;position: absolute;right: 155px;top: 7px;' },
      'flex align-center justify-center app-player-button'
  ); //'div', divStr, {}, 'class'
  let closeBtn = util.createDom('div', divClose, {}, 'app-close-btn');
  let xgControls = player.value.root.querySelector('xg-controls');
  let xgError = player.value.root.querySelector('xg-error');
  xgControls.appendChild(customBtn);
  player.value.root.appendChild(closeBtn);

  // let shot = customBtn.querySelector('.button-screen-shot');
  // let set = customBtn.querySelector('.button-set');
  // let history = customBtn.querySelector('.button-history');
  let closeBtnc = closeBtn.querySelector('.app-close-btn-c');
  let playback = customBtn.querySelector('.button-playback');

  player.value.on('play', () => { });
  player.value.on('focus', () => {
    if (hasCloseBtn) {
      closeBtn.style.display = 'block';
    }
  });
  player.value.on('ended', () => { });
  player.value.on('blur', () => {
    closeBtn.style.display = 'none';
  });

  player.value.on('error', () => { });

  if (closeBtnc) {
    closeBtnc.addEventListener('click', () => {
      closePlayer();
    });
  }

  // 点击视频时间，设置selectIndex
  // player.video.addEventListener('click', () => {
  //     $emit('clickPlayer', index);
  // });
}

const changeVideo = (url: string) => {
  //console.log(player.value)
  player.value.src = url;
}

const closePlayer = () => {
  isPlay.value = false;
  if (player.value) {
    player.value.destroy();
  }
}

const playObjDestroy = () => {
  if (player.value) {
    player.value.destroy();
  }
  console.log('销毁了');
}

defineExpose({
  createPlayer,
  playObjDestroy
})
</script>
